<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="灾害天气记录"></page-header>

        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的灾害内容"
                v-model="searchKeyword"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>

        <view class="list-filter-container">
            <view class="filter-picker" @click="openDatePopup">
                <text class="picker-label">{{ selectedTime || '时间' }}</text>
                <text class="picker-arrow">
                    <roc-icon-plus
                        type="fas"
                        name="angle-down"
                        :size="16"
                        color="#2E6140"></roc-icon-plus>
                </text>
            </view>
            <picker
                mode="selector"
                :range="disasterTypeOptions"
                range-key="name"
                @change="onDisasterTypeChange"
                style="flex: 1">
                <view class="filter-picker">
                    <text class="picker-label">{{ selectedDisasterType?.name || '灾害类型' }}</text>
                    <text class="picker-arrow">
                        <roc-icon-plus
                            type="fas"
                            name="angle-down"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </text>
                </view>
            </picker>
        </view>

        <!-- 日期选择弹出层 -->
        <uni-popup ref="datePopup" type="center">
            <view class="popup-content">
                <view class="popup-title">选择日期范围</view>
                <view class="date-picker-container">
                    <view class="date-item">
                        <text>开始日期：</text>
                        <picker
                            mode="date"
                            :value="tempStartDate || startDate"
                            @change="onStartDateChange">
                            <view class="picker-value">
                                {{ tempStartDate || startDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                    <view class="date-item">
                        <text>结束日期：</text>
                        <picker
                            mode="date"
                            :value="tempEndDate || endDate"
                            :start="tempStartDate || startDate"
                            @change="onEndDateChange">
                            <view class="picker-value">
                                {{ tempEndDate || endDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="popup-buttons">
                    <button class="btn cancel" @click="cancelDatePicker">取消</button>
                    <button class="btn confirm" @click="confirmDatePicker">确定</button>
                </view>
            </view>
        </uni-popup>

        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredDisasterRecords"
                :key="index"
                :item="item"
                @clickItem="viewDetail(item)"
                @edit="editRecord(item.id)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <view style="display: flex; align-items: center">
                            <image
                                style="margin-right: 10rpx"
                                class="icon-wrapper"
                                :src="disasterImgObj[item.disasterType]"
                                mode="aspectFill"></image>
                            <text class="date-text">{{ disasterTextObj[item.disasterType] }}</text>
                        </view>

                        <text class="date-small">{{ formatDate(item.startDate) }}</text>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <div style="display: flex; justify-content: flex-start">
                            <view class="info-row">
                                <text class="info-label">持续时间</text>
                                <text class="info-value">
                                    {{ calculateDuration(item.startDate, item.endDate) }}
                                </text>
                            </view>
                            <view class="info-row">
                                <text class="info-label">灾害程度</text>
                                <text class="info-value">
                                    {{ disasterLevelObj[item.disasterLevel] }}
                                </text>
                            </view>
                        </div>

                        <view class="info-row">
                            <text class="info-label">地块</text>
                            <text class="info-value">{{ item.plotName }}-{{ item.fieldName }}</text>
                        </view>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>
                        <view class="item-images" v-if="item.images">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredDisasterRecords.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 无数据提示 -->
        <empty-data v-if="filteredDisasterRecords.length === 0 && !loading" />
        <view
            class="add-button"
            @click="navigateTo('/pages/agriculture/weatherDisasterManagement/addWeatherDisaster')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { weatherDisaster } from '@/utils/api/index.js'
// 导入格式化函数
import { formatDateChinese, formatImages } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            activeTab: 'all',
            searchKeyword: '',
            disasterRecords: [],
            loading: false,
            loadingMore: false, // 加载更多状态
            hasMore: true, // 是否还有更多数据
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
            // 筛选相关数据
            selectedTime: '',
            selectedDisasterType: '',
            startDate: '',
            endDate: '',
            tempStartDate: '',
            tempEndDate: '',
            disasterTypeOptions: [],
            disasterImgObj: {
                0: '/static/images/gaowen.png',
                1: '/static/images/hanchao.png',
                2: '/static/images/baoyu.png',
                3: '/static/images/ganhan.png',
                4: '/static/images/dafeng.png',
            },
            // 灾害类型的字典
            disastersTypeData: [
                {
                    id: 74,
                    sort: 0,
                    label: '高温',
                    value: '0',
                    dictType: 'disasters_type',
                    status: 0,
                    colorType: '',
                    cssClass: '',
                    remark: null,
                    createTime: 1752832738000,
                },
                {
                    id: 75,
                    sort: 0,
                    label: '寒潮',
                    value: '1',
                    dictType: 'disasters_type',
                    status: 0,
                    colorType: '',
                    cssClass: '',
                    remark: null,
                    createTime: 1752832739000,
                },
                {
                    id: 76,
                    sort: 0,
                    label: '暴雨',
                    value: '2',
                    dictType: 'disasters_type',
                    status: 0,
                    colorType: '',
                    cssClass: '',
                    remark: null,
                    createTime: 1752832740000,
                },
                {
                    id: 80,
                    sort: 0,
                    label: '干旱',
                    value: '3',
                    dictType: 'disasters_type',
                    status: 0,
                    colorType: '',
                    cssClass: '',
                    remark: null,
                    createTime: 1752847180000,
                },
                {
                    id: 81,
                    sort: 0,
                    label: '大风',
                    value: '4',
                    dictType: 'disasters_type',
                    status: 0,
                    colorType: '',
                    cssClass: '',
                    remark: null,
                    createTime: 1752847181000,
                },
            ],
            disasterTextObj: {
                0: '高温',
                1: '寒潮',
                2: '暴雨',
                3: '干旱',
                4: '大风',
            },
            disasterLevelObj: {
                2: '轻度',
                1: '中度',
                0: '重度',
            },
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
        }),
        filteredDisasterRecords() {
            let records = this.disasterRecords
            // 搜索过滤
            if (this.searchKeyword) {
                const keyword = this.searchKeyword.toLowerCase()
                records = records.filter(
                    (record) =>
                        record.name.toLowerCase().includes(keyword) ||
                        record.landBlock.toLowerCase().includes(keyword) ||
                        record.description.toLowerCase().includes(keyword)
                )
            }
            return records
        },
        // 计算当前筛选状态
        hasActiveFilters() {
            return this.selectedTime || (this.selectedDisasterType && this.selectedDisasterType.id)
        },
    },
    onLoad() {
        // 确保字典数据已加载
        this.loadDictData()
    },
    onShow() {
        this.fetchDisasterRecords()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchDisasterRecords()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                uni.showLoading({ title: '加载字典数据...' })

                // 加载灾害类型字典
                await this.getDictByType('weather_disaster_type')
                // 加载灾害程度字典
                await this.getDictByType('disaster_severity')

                // 使用写死的灾害类型数据
                this.disasterTypeOptions = this.disastersTypeData.map((item) => {
                    return {
                        name: item.label,
                        id: item.value,
                    }
                })

                uni.hideLoading()
            } catch (error) {
                console.error('加载字典数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载字典数据失败',
                    icon: 'none',
                })
            }
        },

        // 统一处理筛选变化
        handleFilterChange() {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.disasterType

            // 时间筛选
            if (this.startDate && this.endDate) {
                this.pageParams.startDate = this.startDate
                this.pageParams.endDate = this.endDate
            }
            // 灾害类型筛选
            if (this.selectedDisasterType && this.selectedDisasterType.id) {
                this.pageParams.disasterType = this.selectedDisasterType.id
            }

            // 重新请求接口
            this.fetchDisasterRecords()
        },

        // 处理搜索变化
        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKeyword) {
                this.pageParams.keyword = e || this.searchKeyword
            } else {
                delete this.pageParams.keyword
            }

            // 重新请求接口
            this.fetchDisasterRecords()
        },

        async fetchDisasterRecords(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await weatherDisaster.getDisasterWeatherPage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.disasterRecords = [...this.disasterRecords, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.disasterRecords = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                } else {
                    if (!isLoadMore) {
                        this.disasterRecords = this.getDefaultData()
                    }
                    if (res.msg) {
                        uni.showToast({
                            title: res.msg || '获取数据失败',
                            icon: 'none',
                        })
                    }
                }
            } catch (error) {
                console.error('获取灾害天气记录失败:', error)
                if (!isLoadMore) {
                    uni.showToast({ title: '获取数据失败', icon: 'none' })
                    this.disasterRecords = this.getDefaultData()
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        getDefaultData() {
            return [
                {
                    id: 1,
                    type: 'high-temp',
                    name: '高温',
                    date: '2023-07-15',
                    duration: '3天',
                    severity: '重度',
                    landBlock: '1号地块',
                    description: '导致部分作物叶片枯焦',
                    images: '/static/images/weather/high-temp.png',
                },
                // 其他模拟数据...
            ]
        },

        navigateTo(url) {
            uni.navigateTo({ url })
        },
        formatDate(dateString) {
            return formatDateChinese(dateString)
        },
        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        viewDetail(item) {
            uni.navigateTo({
                url: `/pages/agriculture/weatherDisasterManagement/addWeatherDisaster?id=${item.id}`,
            })
        },

        editRecord(id) {
            uni.navigateTo({
                url: `/pages/agriculture/weatherDisasterManagement/addWeatherDisaster?id=${id}`,
            })
        },

        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条灾害天气记录吗？`,
                success: async (res) => {
                    if (res.confirm) {
                        await this.deleteRecord(item.id)
                    }
                },
            })
        },

        async deleteRecord(id) {
            try {
                uni.showLoading({ title: '删除中...' })
                const res = await weatherDisaster.deleteDisasterWeather(id)
                if (res.code === 0) {
                    this.disasterRecords = this.disasterRecords.filter((record) => record.id !== id)
                    uni.showToast({ title: '删除成功', icon: 'success' })
                } else {
                    uni.showToast({ title: res.msg || '删除失败', icon: 'none' })
                }
            } catch (error) {
                console.error('删除灾害天气记录失败:', error)
                uni.showToast({ title: '删除失败', icon: 'none' })
            } finally {
                uni.hideLoading()
            }
        },

        // 计算持续时间
        calculateDuration(startDate, endDate) {
            if (!startDate || !endDate) return '未知'

            const start = new Date(startDate)
            const end = new Date(endDate)

            // 计算天数差异
            const diffTime = Math.abs(end - start)
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

            if (diffDays === 0) {
                return '1天'
            }

            return `${diffDays}天`
        },

        // 日期选择相关方法
        onStartDateChange(e) {
            this.tempStartDate = e.detail.value
            if (this.tempEndDate && this.tempEndDate < this.tempStartDate) {
                this.tempEndDate = ''
            }
        },

        onEndDateChange(e) {
            this.tempEndDate = e.detail.value
            if (this.tempStartDate && this.tempEndDate < this.tempStartDate) {
                uni.showToast({
                    title: '结束日期不能早于开始日期',
                    icon: 'none',
                })
                this.tempEndDate = this.tempStartDate
            }
        },

        confirmDatePicker() {
            if (this.tempStartDate && this.tempEndDate) {
                if (this.tempEndDate < this.tempStartDate) {
                    uni.showToast({
                        title: '结束日期不能早于开始日期',
                        icon: 'none',
                    })
                    return
                }
                this.startDate = this.tempStartDate
                this.endDate = this.tempEndDate
                this.selectedTime = `${this.startDate} 至 ${this.endDate}`
                this.$refs.datePopup.close()
                this.handleFilterChange()
            } else {
                uni.showToast({
                    title: '请选择开始和结束日期',
                    icon: 'none',
                })
            }
        },

        cancelDatePicker() {
            this.tempStartDate = this.startDate
            this.tempEndDate = this.endDate
            this.$refs.datePopup.close()
        },

        openDatePopup() {
            this.$refs.datePopup.open()
        },

        // 灾害类型选择
        onDisasterTypeChange(e) {
            const index = e.detail.value
            this.selectedDisasterType = this.disasterTypeOptions[index]
            this.handleFilterChange()
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.fetchDisasterRecords(true)
        },

        // 清除所有筛选条件
        clearAllFilters() {
            this.selectedTime = ''
            this.selectedDisasterType = ''
            this.startDate = ''
            this.endDate = ''
            this.tempStartDate = ''
            this.tempEndDate = ''
            this.searchKeyword = ''

            // 清除搜索参数
            delete this.pageParams.keyword
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.disasterType

            // 重新请求接口
            this.fetchDisasterRecords()
        },
    },
}
</script>

<style lang="scss" scoped>
.list-filter-container {
    display: flex;
    justify-content: space-between;
    padding: 10px;
}

.filter-picker {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 5px;
    padding: 10px 12px;
    background-color: #fff;
    border: 1px solid #e5e5e5;
    border-radius: 8px;
    font-size: 15px;
    color: #333;
    position: relative;
    min-width: 0;
    box-sizing: border-box;
}

.picker-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: left;
}

.picker-arrow {
    margin-left: 8px;
    font-size: 13px;
    color: #999;
}

.popup-content {
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 20px;
}

.popup-title {
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
}

.date-picker-container {
    margin-bottom: 20px;
}

.date-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.picker-value {
    flex: 1;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 5px;
    text-align: center;
    width: 300rpx;
}

.popup-buttons {
    display: flex;
    justify-content: space-between;
}

.btn {
    flex: 1;
    margin: 0 5px;
    padding: 10px;
    border-radius: 5px;
    text-align: center;
    font-size: 16px;
}

.cancel {
    background-color: #f5f5f5;
    color: #333;
}

.confirm {
    background-color: #2e6140;
    color: #fff;
}
</style>
